/*
 * =====================================================================================
 *
 *       Filename:  app.c
 *
 *    Description:  测试类
 *    测试驱动程序的ioctl接口控制功能
 *
 *        Version:  1.0
 *        Created:  2015年09月18日 08时24分45秒
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  YOUR NAME (), 
 *   Organization:  
 *
 * =====================================================================================
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <fcntl.h>

#define MEMDEV_IOC_MAGIC    'k'

#define MEMDEV_IOCPRINT _IO(MEMDEV_IOC_MAGIC,1)
#define MEMDEV_IOCGETDATA   _IOR(MEMDEV_IOC_MAGIC,2,int)
#define MEMDEV_IOCSETDATA   _IOW(MEMDEV_IOC_MAGIC,3,int)

static inline void setpos(int fd , int pos){
    printf("ioctl: Call MEMEDEV_IOCSETDATA to set position\n");
    ioctl(fd,MEMDEV_IOCSETDATA , &pos);
}

static inline int getpos(int fd){
    int pos;
    printf("ioctl: Call MEMEDEV_IOCGETDATA to get position\n");
    ioctl(fd,MEMDEV_IOCGETDATA,&pos);
    return pos;
}
int main(int argc, char *argv[])
{
    int fd = 0;
    int arg = 0;
    char buf[256];
    if(-1 == (fd = open("/dev/memdev0",O_RDWR))){
        printf("open dev/memdev0 error");
        _exit(EXIT_FAILURE);
    }
    printf("ioctl:Call MEMDEV_IOCPRINT to printk in driver\n");
    ioctl(fd, MEMDEV_IOCPRINT , &arg);
    strcpy(buf , "this is a test for ioctl!\n");
    printf("write %d bytes in new open file\n",strlen(buf));
    write(fd,buf,strlen(buf));
    printf("new pos is %d\n",getpos(fd));
    
    setpos(fd ,10);
    printf("set pos = 10 \n");
    printf("after setpos (fd,10),new pos is %d\n",getpos(fd));
    close(fd); 
    return 0;
}

